package com.xsq.newmall01.ServiceImpl.MerchantUserServiceImpl;

import com.xsq.newmall01.Dao.Good;
import com.xsq.newmall01.Dao.MerchantUser;
import com.xsq.newmall01.Dao.Ownership;
import com.xsq.newmall01.Exception.ServiceException;
import com.xsq.newmall01.Mapper.MerchantMapper;
import com.xsq.newmall01.Service.MerchantUserService.MGoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("merchantgoodservice")
public class MGoodServiceImpl implements MGoodService {

    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 上架商品：同时插入商品表和所有权表，使用事务保证一致性
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 发生任何异常均回滚
    public void addGood(Good good, int merchantId) {
        // 校验价格不能为负数
        if (good.getPrice() < 0) {
            throw new ServiceException("商品价格不能为负数");
        }
        merchantMapper.insertgood(good);

        // 2. 插入所有权记录到ownership表（关联商家与商品）
        Ownership ownership = new Ownership();
        ownership.setUserid(merchantId);       // 商家ID
        ownership.setGoodid(good.getGoodid()); // 商品ID
        ownership.setUserkind(2);              // 2表示商家（与XML中逻辑一致）
        merchantMapper.insertownership(ownership);
    }

    /**
     * 下架商品：同时删除商品表和所有权表记录，使用事务保证一致性
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 发生任何异常均回滚
    public void removeGood(int goodId, int merchantId) {
        // 0. 校验商品是否属于当前商家（查询ownership表）
        Ownership ownership = merchantMapper.getOwnershipByGoodId(goodId);
        if (ownership == null || ownership.getUserid() != merchantId || ownership.getUserkind() != 2) {
            throw new ServiceException("无权下架该商品（商品不属于当前商家）");
        }
        // 1. 从good表删除商品
        Good good = new Good(goodId); // 仅需商品ID即可
        merchantMapper.deletegood(good);

        // 2. 从ownership表删除对应的所有权记录（校验商家身份）
        Ownership newownership = new Ownership();
        newownership.setUserid(merchantId); // 商家ID（确保删除的是自己的商品）
        newownership.setGoodid(goodId);     // 商品ID
        newownership.setUserkind(2);        // 2表示商家（与XML中逻辑一致）
        merchantMapper.deleteownership(ownership);
    }
    @Override
    @Transactional
    public List<Good> getMerchantOwnedGoods(MerchantUser merchantUser) {
        return merchantMapper.selectownedgoods(merchantUser);
    };

}
